package com.turing.post.common.impl;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;

import javax.ejb.Local;
import javax.ejb.Remote;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.turing.post.common.util.NationCode;
import com.turing.post.common.util.NationCodeDao;
import com.turing.post.util.Config;
import com.turing.post.util.PCPSUtil;

/**
 * @国家地区编码
 * @author zhang xiao pan
 * @创建时间：Dec 15, 2012
 */
@Stateless(mappedName = "common.impl.NationCodeDaoImpl")
@Remote
@Local
public class NationCodeDaoImpl implements NationCodeDao {

	/**
	 * 实体管理器
	 * 
	 * @see javax.persistence.EntityManager
	 */
	@PersistenceContext
	protected EntityManager _em;

	@Override
	public NationCode getNationCodeByNationCodeId(String nationCodeId) {
		return _em.find(NationCode.class, nationCodeId);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<NationCode> getNationCodeList(Integer page, String name) {
		int maxResult = Config.PAGE_SIZE;
		int startPosition = maxResult * page;
		Query query = _em
				.createNativeQuery(
						"select * from NationCode t where nationShortName like ?1 order by nationCodeId",
						NationCode.class).setFirstResult(startPosition)
				.setMaxResults(maxResult);
		if (PCPSUtil.isEmpty(name)) {
			name = "";
		}
		query.setParameter(1, "%" + name + "%");
		return query.getResultList();
	}

	@Override
	public BigInteger getNationCodeTotal(String name) {
		Query query = _em
				.createNativeQuery("select nvl(count(*),0) count from NationCode t where nationShortName like ?1");
		if (PCPSUtil.isEmpty(name)) {
			name = "";
		}
		query.setParameter(1, "%" + name + "%");
		return ((BigDecimal) query.getSingleResult()).toBigInteger();
	}

}
